package plat

import (
	"time"
	"publish/app/account/model"
	"regexp"
	"fmt"
	"encoding/json"
	"strconv"
	"errors"
	"net/url"
)

func init() {
	RegisterPlat("qtt", newplat_qtt())
}

type platqtt struct {
	*plathttp
}


func newplat_qtt() Plat {
	return &platqtt{
		plathttp: &plathttp{
			Host: "https://mpapi.qutoutiao.net",
		},
	}
}

func (p *platqtt) getToken(ck string) string{
	return regSub(ck,`token=([^;]*)`)
}

func regSub(text string,reg string) string {
	regx := regexp.MustCompile(reg)
	elems := regx.FindAllStringSubmatch(text, -1)
	if len(elems) > 0 && len(elems[0]) == 2 {
		return elems[0][1]
	}
	return ""
}


func (p *platqtt) GetProfit(account *model.Account, start, end time.Time) ([]AccountProfit, error) {
	token := p.getToken(account.GetCookie())
	if len(token) == 0{
		return nil,errors.New("cookie 缺失 token")
	}

	api := `https://mpapi.qutoutiao.net/income/detail?page=1&start_date=%s&end_date=%s&token=%s&dtu=200`
	uk := fmt.Sprintf(api, url.QueryEscape(start.Format("2006/01/02")), url.QueryEscape(end.Format("2006/01/02")),token)

	p.setCookie(account.GetCookie())
	bodyBytes, err := p.getReq(uk)
	if err != nil {
		return nil, err
	}

	profits := QttProfits{}
	err = json.Unmarshal(bodyBytes, &profits)
	if err != nil {
		return nil, err
	}

	rets := make([]AccountProfit, 0)
	for _, profit := range profits.Data.Data.List {
		t, err := time.Parse("20060102", profit.Date)
		if err != nil {
			continue
		}
		balance,_ := strconv.ParseFloat( profit.Balance, 64)
		activeBalance,_ := strconv.ParseFloat( profit.ActivityBalance, 64)

		rets = append(rets, AccountProfit{
			AccountId: account.Id,
			Profit:    balance+activeBalance,
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      t.Format("2006-01-02"),
		})
	}

	return rets, nil
}

func (p *platqtt) GetIndex(account *model.Account, start, end time.Time) ([]AccountData, error) {
	return nil, nil
}


func (p *platqtt) GetEveryStatistic(account *model.Account,start,end time.Time)([]EveryDayStatisttic, error){
	return nil,nil
}

func (p *platqtt) GetStatistic(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {
	datas := []AccountStatisttic{}
	news, err := p.getStatisticNews(account, start, end)
	if err != nil {
		fmt.Println("GetStatisticNews:", err.Error())
	} else {
		datas = append(datas, news...)
	}

	videos, err := p.getStatisticVideo(account, start, end)
	if err != nil {
		fmt.Println("GetStatisticVideo :", err.Error())
	} else {
		datas = append(datas, videos...)
	}

	return datas,nil
}

func (p *platqtt) getStatisticNews(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {
	token := p.getToken(account.GetCookie())
	if len(token) == 0{
		return nil,errors.New("cookie 缺失 token")
	}

	api := `https://mpapi.qutoutiao.net/report/content?start_date=%s&end_date=%s&token=%s&dtu=200`
	uk := fmt.Sprintf(api, start.Format("2006-01-02"), end.Format("2006-01-02"),token)

	p.setCookie(account.GetCookie())
	bodyBytes, err := p.getReq(uk)
	if err != nil {
		return nil, err
	}

	statistic := QttStat{}
	err = json.Unmarshal(bodyBytes, &statistic)
	if err != nil {
		return nil, err
	}
	datas := []AccountStatisttic{}
	for _, data := range statistic.Data.Data {
		read,_ := strconv.ParseInt( data.Pv, 10, 64)
		recommend,_ := strconv.ParseInt( data.ListPv, 10, 64)
		datas = append(datas, AccountStatisttic{
			AccountId: account.Id,
			Num:       read, //阅读量
			Type:      "reads_news",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.PublishTime,
		}, AccountStatisttic{
			AccountId: account.Id,
			Num:       recommend, //推荐量
			Type:      "recommends_news",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.PublishTime,
		})
	}

	return datas, nil
}

func (p *platqtt) getStatisticVideo(account *model.Account, start, end time.Time) ([]AccountStatisttic, error) {

	token := p.getToken(account.GetCookie())
	if len(token) == 0{
		return nil,errors.New("cookie 缺失 token")
	}

	api := `https://mpapi.qutoutiao.net/report/video?start_date=%s&end_date=%s&token=%s&dtu=200`
	uk := fmt.Sprintf(api, start.Format("2006-01-02"), end.Format("2006-01-02"),token)

	p.setCookie(account.GetCookie())
	bodyBytes, err := p.getReq(uk)
	if err != nil {
		return nil, err
	}

	statistic := QttStat{}
	err = json.Unmarshal(bodyBytes, &statistic)
	if err != nil {
		return nil, err
	}
	datas := []AccountStatisttic{}
	for _, data := range statistic.Data.Data {
		read,_ := strconv.ParseInt( data.Pv, 10, 64)
		recommend,_ := strconv.ParseInt( data.ListPv, 10, 64)

		datas = append(datas, AccountStatisttic{

			AccountId: account.Id,
			Num:       read, //播放量
			Type:      "reads_video",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.PublishTime,
		}, AccountStatisttic{
			AccountId: account.Id,
			Num:       recommend, //推荐量
			Type:      "recommends_video",
			Time:      time.Now().Format("2006-01-02 15:04:05"),
			Date:      data.PublishTime,
		})
	}

	return datas, nil
}

func (p *platqtt) GetLevel(account *model.Account) (string, error) {
	return "",nil
}

func (p *platqtt) GetArticles(account *model.Account, start time.Time, end time.Time) ([]Article, error) {
	articles := []Article{}
	page := 1

	token := p.getToken(account.GetCookie())
	if len(token) == 0{
		return nil,errors.New("cookie 缺失 token")
	}

	for {
		api := fmt.Sprintf(`https://mpapi.qutoutiao.net/content/getList?status=&page=%d&title=&token=%s&dtu=200`,page,token)
		p.setCookie(account.GetCookie())
		bodyBytes, err := p.getReq(api)
		if err != nil {
			return nil, err
		}

		datas :=  QttArticle{}
		if err := json.Unmarshal(bodyBytes,&datas);err != nil{
			return nil,err
		}

		fmt.Println("page:",page)
		fmt.Println("datas:",datas)

		if datas.Code != 0 || len(datas.Data.Data) == 0{
			return articles,nil
		}

		for _,data := range datas.Data.Data{
			statusMsg := ""
			status := 0
			if data.Status == "1"{
				status = 3
				statusMsg = "审核中"
			}

			if data.Status == "3"{
				status = 4
				statusMsg = "发布失败"
			}

			if data.Status == "2"{
				status = 1
			}

			t,_ := time.Parse("2006-01-02 15:04:05",data.PublishTime)

			if t.Before(start){
				return articles,nil
			}

			if t.After(start) && t.Before(end) {
				articles = append(articles, Article{
					Title:   data.Title,
					Url:     data.Url,
					Time:    t,
					Status:  status,
					FailMsg: statusMsg,
				})
			}
		}

		page++
	}
	return articles,nil
}

func (p *platqtt) GetPayRecord(account *model.Account, start time.Time, end time.Time) ([]PayRecord, error) {
	return nil,nil
}

func (p *platqtt) GetFinancialInformation(account *model.Account) (*FinancialInformation, error) {
	return nil,nil
}

